import api from './api'
import type {
  CoreMetricsDto,
  StatisticsQueryDto,
  StatisticsDto,
  PagedResultDto,
  AnnouncementQueryDto,
  AnnouncementDto,
  PurchaseOrderQueryDto,
  PurchaseOrderDto,
  ProductionOrderQueryDto,
  ProductionOrderDto,
  ProductionSalesOrderQueryDto,
  ProductionSalesOrderDto,
  ApprovalDocumentQueryDto,
  ApprovalDocumentDto,
  WarehouseQueryDto,
  WarehouseDto,
  ProductionItemQueryDto,
  ProductionItemDto,
  ProcessQueryDto,
  ProcessDto,
  ChartDataDto
} from '@/types/console'
import type { ApiResult } from '@/types/auth'

// 控制台API服务
export const consoleApi = {
  // 获取今日核心指标
  async getTodayMetrics(): Promise<ApiResult<CoreMetricsDto>> {
    try {
      const response = await api.get('/Dashboard/today-metrics')
      return response.data
    } catch (error: any) {
      console.error('获取今日核心指标失败:', error)
      return {
        msg: '获取今日核心指标失败',
        code: 500,
        data: {} as CoreMetricsDto
      }
    }
  },

  // 获取核心指标数据
  async getCoreMetrics(startDate?: string, endDate?: string): Promise<ApiResult<CoreMetricsDto[]>> {
    try {
      const params = new URLSearchParams()
      if (startDate) params.append('startDate', startDate)
      if (endDate) params.append('endDate', endDate)
      
      const response = await api.get(`/Dashboard/core-metrics?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取核心指标数据失败:', error)
      return {
        msg: '获取核心指标数据失败',
        code: 500,
        data: []
      }
    }
  },

  // 获取统计数据
  async getStatistics(query: StatisticsQueryDto): Promise<ApiResult<StatisticsDto[]>> {
    try {
      const params = new URLSearchParams()
      if (query.startDate) params.append('startDate', query.startDate)
      if (query.endDate) params.append('endDate', query.endDate)
      if (query.type) params.append('type', query.type)
      if (query.timeRange) params.append('timeRange', query.timeRange)
      
      const response = await api.get(`/Dashboard/statistics?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取统计数据失败:', error)
      return {
        msg: '获取统计数据失败',
        code: 500,
        data: []
      }
    }
  },

  // 获取销售统计图表数据
  async getSalesChartData(timeRange: string = 'week'): Promise<ApiResult<ChartDataDto>> {
    try {
      const response = await api.get(`/Dashboard/sales-chart?timeRange=${timeRange}`)
      return response.data
    } catch (error: any) {
      console.error('获取销售图表数据失败:', error)
      return {
        msg: '获取销售图表数据失败',
        code: 500,
        data: {} as ChartDataDto
      }
    }
  },

  // 获取采购统计图表数据
  async getPurchaseChartData(timeRange: string = 'week'): Promise<ApiResult<ChartDataDto>> {
    try {
      const response = await api.get(`/Dashboard/purchase-chart?timeRange=${timeRange}`)
      return response.data
    } catch (error: any) {
      console.error('获取采购图表数据失败:', error)
      return {
        msg: '获取采购图表数据失败',
        code: 500,
        data: {} as ChartDataDto
      }
    }
  },

  // 获取通知公告列表
  async getAnnouncements(query: AnnouncementQueryDto): Promise<ApiResult<PagedResultDto<AnnouncementDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.type) params.append('type', query.type)
      if (query.isActive !== undefined) params.append('isActive', query.isActive.toString())
      
      const response = await api.get(`/Announcement?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取通知公告列表失败:', error)
      return {
        msg: '获取通知公告列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取审批单据列表
  async getApprovalDocuments(query: ApprovalDocumentQueryDto): Promise<ApiResult<PagedResultDto<ApprovalDocumentDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.documentType) params.append('documentType', query.documentType)
      if (query.status) params.append('status', query.status)
      
      const response = await api.get(`/ApprovalDocument?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取审批单据列表失败:', error)
      return {
        msg: '获取审批单据列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取采购订单列表
  async getPurchaseOrders(query: PurchaseOrderQueryDto): Promise<ApiResult<PagedResultDto<PurchaseOrderDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.status) params.append('status', query.status)
      if (query.orderType) params.append('orderType', query.orderType)
      
      const response = await api.get(`/Dashboard/purchase-orders?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取采购订单列表失败:', error)
      return {
        msg: '获取采购订单列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取生产工单列表
  async getProductionOrders(query: ProductionOrderQueryDto): Promise<ApiResult<PagedResultDto<ProductionOrderDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.status) params.append('status', query.status)
      if (query.responsiblePerson) params.append('responsiblePerson', query.responsiblePerson)
      
      const response = await api.get(`/Dashboard/production-orders?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取生产工单列表失败:', error)
      return {
        msg: '获取生产工单列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取销售订单列表
  async getSalesOrders(query: ProductionSalesOrderQueryDto): Promise<ApiResult<PagedResultDto<ProductionSalesOrderDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.status) params.append('status', query.status)
      if (query.customerName) params.append('customerName', query.customerName)
      
      const response = await api.get(`/Dashboard/sales-orders?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取销售订单列表失败:', error)
      return {
        msg: '获取销售订单列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取仓库列表
  async getWarehouses(query: WarehouseQueryDto): Promise<ApiResult<PagedResultDto<WarehouseDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.warehouseType) params.append('warehouseType', query.warehouseType)
      if (query.status) params.append('status', query.status)
      
      const response = await api.get(`/Warehouse?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取仓库列表失败:', error)
      return {
        msg: '获取仓库列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取生产物品列表
  async getProductionItems(query: ProductionItemQueryDto): Promise<ApiResult<PagedResultDto<ProductionItemDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.itemType) params.append('itemType', query.itemType)
      if (query.warehouseId) params.append('warehouseId', query.warehouseId.toString())
      
      const response = await api.get(`/ProductionItem?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取生产物品列表失败:', error)
      return {
        msg: '获取生产物品列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  },

  // 获取工序列表
  async getProcesses(query: ProcessQueryDto): Promise<ApiResult<PagedResultDto<ProcessDto>>> {
    try {
      const params = new URLSearchParams()
      params.append('pageIndex', query.pageIndex.toString())
      params.append('pageSize', query.pageSize.toString())
      if (query.keyword) params.append('keyword', query.keyword)
      if (query.status) params.append('status', query.status)
      if (query.processType) params.append('processType', query.processType)
      
      const response = await api.get(`/Process?${params.toString()}`)
      return response.data
    } catch (error: any) {
      console.error('获取工序列表失败:', error)
      return {
        msg: '获取工序列表失败',
        code: 500,
        data: {
          items: [],
          totalCount: 0,
          pageIndex: 1,
          pageSize: 10,
          totalPages: 0
        }
      }
    }
  }
}

export default consoleApi 